<?php

namespace app\api\model;

use think\Db;
use think\Exception;
use think\Model;
use app\common\model\Order;
use think\model\Merge;

class ShopOrder extends Merge
{
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $resultSetType = 'collection';
    protected $hidden = ['id','mp_id','trans_id','openid','user_id','coupon_id'];

    const ORDER_WAIT_PAY = 1;               //待付款
    const ORDER_WAIT_SEND = 2;              //已付款,待发货
    const ORDER_WAIT_SIGN = 3;           //已发货,待收货
    const ORDER_WAIT_COMMENT = 4;           //已收货,待评价
    const ORDER_COMPLETE = 5;               //完成

    const ORDER_RETURN_REQUEST = 6;         //申请退货 协商中(退货,换货)
    const ORDER_RETURN_REFUSE = 7;          //店家拒绝
    const ORDER_RETURN_OK = 8;              //已退款
    const ORDER_INVALID = 9;                //失效

    // 定义关联模型列表
    protected $table = 'uct_shop_order';
    protected $relationModel = ['ShopOrderItem'];
    protected $fk = 'order_id';
    protected $mapFields = [
        'id'        =>  'ShopOrder.id',
        'itemId'        =>  'ShopOrderItem.id'
    ];

    protected function base($query)
    {
        $mpId = get_api_applet_id();
        $globalKey = [
            'mp_id'=>$mpId
        ];
        $query->where($globalKey);
    }

    public function shopOrderItems()
    {
        return $this->hasMany('ShopOrderItem','order_id','id');
    }

    public static function getList($map = [], $page = 1, $row = 10)
    {
        $hidden = [
            'payment_time','shipping_time','check_time','refund_time',
            'buy_remarks','refund_remarks','admin_remarks'];
        $sort = ['create_time' => 'desc'];
        $data = self::where($map)
            ->field($hidden,true)
            ->with('shopOrderItems')
            ->page($page,$row)
            ->order($sort)
            ->select();
        $res['data'] = !$data ? [] : $data->toArray();
        $total = self::where($map)->count();
        $res['has_more'] = ceil($total / $row) > $page ? true : false;
        return $res;
    }

    //获取单个商品
    public static function getByOrderNo($orderNo,$userId)
    {
        $map = [
            'order_no' => $orderNo,
            'user_id' => $userId,
        ];
        $res['data'] = self::where($map)
            ->with('shopOrderItems')
            ->find();
        return $res;
    }

    //取消订单
    public static function cancelById($orderNo, $userId)
    {
        $map = [
            'order_no' => $orderNo,
            'user_id' => $userId,
            'status' => self::ORDER_WAIT_PAY
        ];
        $order = self::get($map);
        if(!$order){
            return ['_code' => 400, 'msg' => '订单不存在'];
        }else{
            $res = $order->delete();
            if ($res > 0){
                $code = $order['coupon_code'];
                $code = WechatCardCode::onlyTrashed()
                    ->where(['decrypt_code'=>$order['coupon_code']])
                    ->find();
                $r = $code->restore();
                return ['_code' => 201, 'msg' => '操作成功'];
            }
            else
                return ['_code' => 500, 'msg' => '操作失败'];
        }
    }

    //签收订单
    public static function signById($orderNo, $userId)
    {
        $map = [
            'order_no' => $orderNo,
            'user_id' => $userId,
            'status' => self::ORDER_WAIT_SIGN
        ];
        $order = self::get($map);
        if(!$order){
            return ['_code' => 400, 'msg' => '订单不存在'];
        }else{
            $order->status =self::ORDER_WAIT_COMMENT;
            $res = $order->save();
            if ($res > 0)
                return ['_code' => 201, 'msg' => '操作成功'];
            else
                return ['_code' => 500, 'msg' => '操作失败'];
        }
    }

    //订单售后
    public static function refundById($orderNo, $userId, $remarks)
    {
        if($remarks == '')
            return ['_code' => 400, 'msg' => '备注不能为空'];
        $map = [
            'order_no' => $orderNo,
            'user_id' => $userId,
            //排除 已评价、未支付 订单
            'status' => ['NOT IN',
                [   self::ORDER_WAIT_PAY,
                    self::ORDER_RETURN_REQUEST,
                    self::ORDER_RETURN_REFUSE,
                    self::ORDER_RETURN_OK]
            ],
        ];
        $order = self::get($map);
        if(!$order){
            return ['_code' => 400, 'msg' => '订单不存在'];
        }else{
            $order->status = self::ORDER_RETURN_REQUEST;
            $order->refund_remarks = $remarks;
            $res = $order->save();
            if ($res > 0)
                return ['_code' => 201, 'msg' => '操作成功'];
            else
                return ['_code' => 500, 'msg' => '操作失败'];
        }
    }


    public function getContactAttr($value)
    {
        return explode('-',$value);
    }
    public function getCreateTimeAttr($value)
    {
        $value = empty($value) ? '-' : date('Y-m-d H:i:s', $value);
        return $value;
    }
    public function getPaymentTimeAttr($value)
    {
        $value = empty($value) ? '-' : date('Y-m-d H:i:s', $value);
        return $value;
    }
    public function getShippingTimeAttr($value)
    {
        $value = empty($value) ? '-' : date('Y-m-d H:i:s', $value);
        return $value;
    }
    public function getCheckTimeAttr($value)
    {
        $value = empty($value) ? '-' : date('Y-m-d H:i:s', $value);
        return $value;
    }
    public function getRefundTimeAttr($value)
    {
        $value = empty($value) ? '-' : date('Y-m-d H:i:s', $value);
        return $value;
    }

    /*  生成订单编号*/
    public static function generateOrderCode()
    {
        date_default_timezone_set("PRC");
        $prefix = 'A' . chr(85 - date('m')) . chr(65 + date('d') % 26);
        $orderSn = $prefix . date('dd') . substr(time(), -4) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }
}
